const app = getApp();
var util = require('../../utils/util.js');

Page({
  data: {
    img1: '/pages/img/qr.png',
    img2: '/pages/img/image_complete.png',
    img3: '/pages/img/image_sending.png',
    img4: '/pages/img/image_sending2.png',
    num1: '1',
    badge1: 'badge_gray',
    num2: '2',
    badge2: 'badge_gray',
    num3: '3',
    badge3: 'badge_gray',
    num4: '4',
    badge4: 'badge_gray',
    today: util.formatDay(new Date()),
    result: '',
    time: "00:00:00",
    date: util.formatDay(new Date()),
    time2: "00:00:00",
    date2: util.formatDay(new Date()),
    array: [], // 初始化按钮数组
    line: {}, // 存储线路信息
    driver: {}, // 存储司机信息
    istrue: false, // 控制弹窗显示
  },

  onLoad: function (options) {

    wx.setNavigationBarTitle({
      title: '首页'
    });
    this.initTimes(); // 初始化时间按钮
    getApp().day = util.formatDay(new Date());
  },
  onShow: function (options) {
    this.getTabBar().setData({
      current: 'index'
    })
  },

  onShareAppMessage() {
    return {
      title: "定邦小程序",
      path: "pages/index/index",
    };
  },

  onShareTimeline() {
    return {
      title: "定邦小程序",
      path: "pages/index/index",
    };
  },

  // 显示picker
  showPicker: function () {
    // 这里可以添加额外的逻辑，比如动画效果等
  },

  // 选择日期后调用
  bindTodayChange: function (e) {
    const date = e.detail.value;
    
    app.day = date;
    this.setData({
      today: date,
    });
  },

  // 检测下拉刷新事件
  onPullDownRefresh: function () {
    wx.stopPullDownRefresh();
  },

  tp: function (e) {
    wx.navigateTo({
      url: "/pages/orders2/orders2?day=" + this.data.today + "&ordersType=0"
    });
  },

  wc: function (e) {
    wx.navigateTo({
      url: "/pages/orders2/orders2?day=" + this.data.today + "&ordersType=1"
    });
  },

  upCode: function (e) {
    this.setData({
      upCode: e.detail.value,
    });
  },

  upWeight: function (e) {
    this.setData({
      upWeight: e.detail.value,
    });
  },

  downCode: function (e) {
    this.setData({
      downCode: e.detail.value,
    });
  },

  downWeight: function (e) {
    this.setData({
      downWeight: e.detail.value,
    });
  },

  bindTimeChange: function (e) {
    this.setData({
      time: e.detail.value + ":00",
    });
  },

  bindDateChange: function (e) {
    this.setData({
      date: e.detail.value,
    });
  },

  bindTimeChange2: function (e) {
    this.setData({
      time2: e.detail.value + ":00",
    });
  },

  bindDateChange2: function (e) {
    this.setData({
      date2: e.detail.value,
    });
  },

  // 关闭弹窗
  closeDialog: function () {
    this.setData({
      istrue: false,
    });
  },

  saveDialog: function () {
    var data = {
      orderTime: util.formatTime(new Date()),
      lineName: this.data.line.lineName,
      lineId: this.data.line.lineId,
      startCity: this.data.line.startCity,
      endCity: this.data.line.endCity,
      customerName: this.data.line.customerName,
      orderType: this.data.line.orderType,
      transType: this.data.line.transType,
      saleName: this.data.line.saleName,
      saleId: this.data.line.saleId,
      goodsName: this.data.line.goodsName,

      driverName: this.data.driver.driverName,
      driverId: this.data.driver.driverId,
      driverMobile: this.data.driver.driverMobile,
      carNum: this.data.driver.carNum,
      carrierName: this.data.driver.carrierName,
      carrierId: this.data.driver.carrierId,
      transLevel: this.data.driver.transLevel,
      accountName: this.data.driver.accountName,
      accountNum: this.data.driver.accountNum,
      financeType: this.data.driver.financeType,

      upCode: this.data.upCode,
      upWeight: this.data.upWeight,
      downCode: this.data.downCode,
      downWeight: this.data.downWeight,
      upTime: this.data.date + " " + this.data.time,
      downTime: this.data.date2 + " " + this.data.time2,
    };

    wx.request({
      url: app.serverIP + '/kkl/cms/app/OrdersCarrier/add?token=' + app.token,
      method: "POST",
      data: JSON.stringify(data),
      contentType: "application/json",
      success: (res) => {
        if (res.data.code == "200") {
          wx.showToast({
            title: "操作成功",
            icon: 'none',
            duration: 2000
          });
          this.setData({
            istrue: false,
          });
        } else {
          wx.showToast({
            title: "修改失败:" + res.data.code,
            icon: 'none',
            duration: 2000
          });
          console.log(res.data.message);
        }
      },
    });
  },

  // 使点击的按钮高亮
  btnclick: function (e) {
    const day = e.target.id;
    const updatedArray = this.data.array.map(item => ({
      ...item,
      type: item.day === day ? "btn-select" : "btn"
    }));

    this.setData({
      array: updatedArray,
      today: day.replace(/\//g, '-'),
    });

    app.day = day;
  },

  getScancode: function () {
    if (!this.isLogin()) {
      wx.showToast({
        title: "请先登录系统才能进行扫码接单!",
        icon: 'none',
        duration: 2000
      });
      return;
    }

    wx.scanCode({
      success: (res) => {
        const result = res.result;

        wx.request({
          url: app.serverIP + '/kkl/cms/app/Line/' + result + '?token=' + app.token,
          dataType: "json",
          success: (res) => {
            this.setData({
              lineName: res.data.data.name,
              line: res.data.data,
            });
          },
        });

        wx.request({
          url: app.serverIP + '/kkl/cms/app/CarDriver/' + app.id + '?token=' + app.token,
          dataType: "json",
          success: (res) => {
            this.setData({
              driver: res.data.data,
            });
          },
        });

        this.openDialog();
      },
      fail: () => {
        wx.showToast({
          title: '扫码失败,请重新尝试扫描线路二维码',
          icon: 'loading',
          duration: 1500
        });
      },
    });
  },

  initTimes: function () {
    let days = [];
    for (let i = 0; i < 8; i++) {
      days.unshift(this.getWeek(i));
    }
    this.checkBtn(days);
  },

  checkBtn: async function (days) {
    try {
      const windowInfo = await wx.getWindowInfo();
      this.setData({
        className_height: windowInfo.windowHeight / days.length,
        array: days,
      });
    } catch (error) {
      console.error('Failed to get window info:', error);
    }
  },

  getWeek: function (i) {
    const now = new Date();
    const firstDay = new Date(now - i * 86400000);
    const mon = Number(firstDay.getMonth()) + 1;
    const year = Number(firstDay.getFullYear());
    const btn_type = i === 0 ? "btn-select" : "btn";

    return {
      day: `${year}/${mon}/${firstDay.getDate()}`,
      num: firstDay.getDate(),
      type: btn_type,
    };
  },

  isLogin: function () {
    return !!app.userInfo;
  },

  openDialog: function () {
    this.setData({
      istrue: true,
    });
  }
});